package zhongbo.java.websocket.demo.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import zhongbo.java.websocket.demo.model.User;
import zhongbo.java.websocket.demo.service.IOnlineUserService;
import zhongbo.java.websocket.demo.service.IUserService;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 说明：
 *
 * @author 钟波dellNotebook
 * @since 2025年03月24日 星期一 03:36:05
 */
@Service
@Slf4j
public class OnlineUserServiceImpl implements IOnlineUserService {

    private static final String ONLINE_USERS_KEY = "chat:online_users";
    private static final String USER_INFO_KEY = "user:";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private IUserService userService;

    @Override
    public void userLogin(String userId) {
        User user = userService.findOne(userId);
        if (user == null) {
            return;
        }
        redisTemplate.opsForSet().add(ONLINE_USERS_KEY, userId + "::" + user.getName());
        redisTemplate.expire(ONLINE_USERS_KEY, 1, TimeUnit.DAYS);
    }

    @Override
    public void userLogout(String userId) {
        redisTemplate.opsForSet().remove(ONLINE_USERS_KEY, userId);
    }

    @Override
    public Set<String> getOnlineUsers() {
        return redisTemplate.opsForSet().members(ONLINE_USERS_KEY);
    }

    @Override
    public User changeName(String userId, String name) {
        User user = userService.findOne(userId);
        if (user != null) {
            user.setName(name);
            User edit = userService.edit(user);
            if (edit != null) {
                redisTemplate.opsForSet().add(ONLINE_USERS_KEY, userId + "::" + user.getName());
                redisTemplate.expire(ONLINE_USERS_KEY, 1, TimeUnit.DAYS);
                return edit;
            }
        }
        return null;
    }
}
